﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace 智信科技物流系统
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        private void Main_Load(object sender, EventArgs e)
        {
            skinEngine1.SkinFile = "DeepCyan.ssk";
            
            login log = new login();//创建login
            log.ShowDialog();
            if (!firstload.exit)//即使close了，load事件也会全部执行完毕后，程序才彻底结束，因此后面的代码要限制防止加载
            {

                Load load = new Load();
                load.Show();
                Application.DoEvents();
                initial();//初始化各项控件,以及赋初值
                load.Close();
                this.WindowState = FormWindowState.Maximized;
                //     lb_status.Text = "加载完成";
                this.Focus();

            }
            else
                Application.Exit();
        }
        private void initial()
        {

            //cmb_dressday.SelectedIndex = 0;//设定显示几天以内
            //初始化datagridview，设定列
            cmb_dress.SelectedIndex = 0;
            dg_main.Columns.Add("trueid", "trueid");
            dg_main.Columns["trueid"].Visible = false;
            dg_main.Columns.Add("id", "id");
            dg_main.Columns.Add("DepartureCity", "DepartureCity");
            dg_main.Columns.Add("content", "content");
            dg_main.Columns["content"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;


            Dao dao = new Dao();
            DateTime t = DateTime.Now.Date;
            //   t = t.AddDays(-31);//test
            string cmd = "select * from bm_Release where (DepartureTime>'"
                        + t.ToString("yyyy-MM-dd HH:mm") + "') order by id asc";
            dao.GetLogistics(cmd);//将数据存储到缓存区
            //    loadprogress.Maximum = dao.GetNum(1);
            //    loadprogress.Value = 0;
            //   dao.BindMainDataGridView(dg_main, 1, loadprogress, lb_status);//带进度条的旧版语句
            dao.BindDataGridView(dg_main, 1);//把缓冲区的1天以内的数据写入主窗体的dg  
            //myThread = new Thread(DoData);
            //myThread.IsBackground = true;
        }
        // 刷新主窗体的datagridview
        //Thread myThread;
        //private void bind(int k)
        //{
        //    myThread = new Thread(DoData);
        //    myThread.IsBackground = true;
        //    myThread.Start(k + 1);
        //}


        private void listen()
        {
            Thread t_see = new Thread(see);
            t_see.IsBackground = true;
            t_see.Start();
            /*
            Thread t_update = new Thread(update);
            t_update.IsBackground = true;
            t_update.Start();
            */
        }
        /*
        private void update()//从本地缓存更新数据到datagridview
        {
            while (true)
            {
                Dao dao = new Dao();
                dg_main.Invoke(new MethodInvoker(delegate
                {

                    int maxid = Convert.ToInt32(dg_main.Rows[dg_main.Rows.Count - 1].Cells["trueid"].Value);

                    DateTime time = DateTime.Now.Date;
                    int t = cmb_dressday.SelectedIndex;
                    time = time.AddDays(-t);//获取九天以内的全部信息
                    for (int i = 0; i < Logistics.list.Count; i++)
                    {
                        if (Convert.ToDateTime(Logistics.list[i].DepartureTime1) <= time) continue;//去掉时间不符合的
                        if (Convert.ToInt32(Logistics.list[i].Id) > maxid)
                        {
                            dg_main.Rows.Add(dao.Deal(dg_main, Logistics.list[i]));
                            this.Text = "QQCTU物流 当前信息数量:" + dg_main.Rows.Count;
                            Application.DoEvents();
                        }
                    }
                }));

                Thread.Sleep(500);
            }
        }

        */
        //private delegate void DoDataDelegate(object number);
        //private void DoData(object number)
        //{
        //    if (loadprogress.InvokeRequired)
        //    {
        //        DoDataDelegate d = DoData;
        //        loadprogress.Invoke(d, number);
        //    }
        //    else
        //    {
        //        Dao dao = new Dao();
        //        loadprogress.Maximum = dao.GetNum((int)number);
        //        loadprogress.Value = 0;
        //        dao.BindMainDataGridView(dg_main, (int)number, loadprogress, lb_status);

        //    }

        //}

        private void see()
        {
            Dao dao = new Dao();
            while (true)
            {
                if (!something.loaded) continue;//如果没加载完成，即Logistics还被占用，则放弃这次更新     
                string maxid = Logistics.list[Logistics.list.Count - 1].Id;//取出旧数据最大id                
                string cmd = "select * from bm_Release where ( id >" + maxid + ") order by id asc";
                List<oneLogistics> templist = new List<oneLogistics>();//存储缓冲数据              
                dao.GetLogistics(templist, cmd);
                if (templist.Count > 0)
                {
                    Logistics.list.AddRange(templist);
                    for (int i = 0; i < templist.Count; i++)
                    {
                        dg_main.Invoke(new MethodInvoker(delegate
                        {
                            dg_main.Rows.Add(dao.Deal(dg_main, templist[i]));
                            this.Text = "QQCTU物流 当前信息数量:" + dg_main.Rows.Count;
                            if (dg_main.Rows.Count > 0 && chk_lock.Checked)
                                dg_main.FirstDisplayedScrollingRowIndex = dg_main.Rows.Count - 1;
                            Application.DoEvents();
                        }));
                    }
                }

            }
        }

        private void timer_listen_Tick(object sender, EventArgs e)
        {
            /*
            if (!something.loaded) return;//如果没加载完成，即Logistics还被占用，则放弃这次更新

            DateTime t = DateTime.Now.Date;
            t = t.AddDays(-(cmb_dressday.SelectedIndex));//获取九天以内的全部信息
            string cmd = "select * from bm_Release where (DepartureTime>'"
                            + t.ToString("yyyy-MM-dd HH:mm") + "') order by id asc";

            int sum = Logistics.list.Count;//取出旧数据条数
            Logistics.list.Clear();
            dao.GetLogistics(cmd);//获取新数据
            List<oneLogistics> newone = Logistics.list;//取出新数据          
            for (int i = sum + 1; i < newone.Count; i++)
            {
                dg_main.Rows.Add(dao.Deal(dg_main, newone[i]));
            }
            */

        }


        private void dg_main_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {

        }

        private void cmb_dressday_SelectedIndexChanged(object sender, EventArgs e)
        {


        }

        private void cmb_dressday_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //if (myThread.IsAlive)
            //{
            //    myThread.Abort();
            //    myThread.Join();
            //}

            //dg_main.Rows.Clear();
            //bind(cmb_dressday.SelectedIndex);

        }

        private void cmb_dress_SelectedIndexChanged(object sender, EventArgs e)
        {
            //       lb_status.Text = "正在筛选数据";
            //     Application.DoEvents();
            //////
            //   loadprogress.Maximum = dg_main.Rows.Count;
            if (cmb_dress.SelectedIndex == 0)
                for (int i = 0; i < dg_main.Rows.Count; i++)
                {
                    dg_main.Rows[i].Visible = true;
                    //     Application.DoEvents();
                }
            if (cmb_dress.SelectedIndex == 1)
                for (int i = 0; i < dg_main.Rows.Count; i++)
                {
                    if (dg_main.Rows[i].DefaultCellStyle.ForeColor == Color.Blue)
                        dg_main.Rows[i].Visible = false;
                    else
                        dg_main.Rows[i].Visible = true;
                    //   Application.DoEvents();
                }
            if (cmb_dress.SelectedIndex == 2)
                for (int i = 0; i < dg_main.Rows.Count; i++)
                {
                    if (dg_main.Rows[i].DefaultCellStyle.ForeColor == Color.Blue)
                        dg_main.Rows[i].Visible = true;
                    else
                        dg_main.Rows[i].Visible = false;
                    //     loadprogress.Value += 1;
                    //    Application.DoEvents();
                }

            //  lb_status.Text = "筛选完成";
        }

        private void lb_status_TextChanged(object sender, EventArgs e)
        {
            this.Text = "QQCTU物流 当前信息数量:" + dg_main.Rows.Count;
        }

        private void Main_Shown(object sender, EventArgs e)
        {

            Application.DoEvents();
            Thread t_bgload = new Thread(bgload);
            View frm_history = new View();
            //初始化datagridview，设定列
            frm_history.dg_view.Columns.Add("trueid", "trueid");
            frm_history.dg_view.Columns["trueid"].Visible = false;
            frm_history.dg_view.Columns.Add("id", "id");
            frm_history.dg_view.Columns.Add("DepartureCity", "DepartureCity");
            frm_history.dg_view.Columns.Add("content", "content");
            frm_history.dg_view.Columns["content"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            t_bgload.Start();

        }
        /* 在后台获取数据库中相关数据，这样先加载界面，后更新数据，加快打开速度
         * 下面几个过程的加载的顺序是根据依赖关系来排列的，所以不能改变顺序！！！！
         * 否则后果自负，噗哈~（超高校级的张昊）
        */
        private void bgload()
        {

            Dao dao = new Dao();

            //加载历史记录,必须放在listen（）前面，否则会出错！！！
            DateTime t = DateTime.Now.Date;
            t = t.AddDays(-2);//获取十天以内的全部信息
            string cmd = "select * from bm_Release where (DepartureTime>'"
            + t.ToString("yyyy-MM-dd HH:mm") + "') order by id asc";
            Logistics.list.Clear();
            dao.GetLogistics(cmd);//将数据存储到缓存区
            btn_history.Invoke(new MethodInvoker(delegate
            {
                btn_history.Text = "历史数据";
                btn_history.Enabled = true;

            }));
            //历史记录加载完成

            listen();//开始后台监听数据库更新

       
            //准备发布按钮
                 //加载省市数据库
            Wordthing.Province = dao.sqlSelect("select * from AreaFull");
                //加载用户自定义短语
            Wordthing.UserPhrase = dao.sqlSelect("select WordContent from bm_Commonword");
            btn_release.Invoke(new MethodInvoker(delegate
            {
                btn_release.Enabled = true;
                btn_release.Text = "发布";
            }));
            //发布准备完成







           




            
           

        }

        private void btn_history_Click(object sender, EventArgs e)
        {
            View frm_history = new View();
            Dao dao = new Dao();
            btn_history.Text = "正在打开";
            Application.DoEvents();
            //初始化datagridview
            frm_history.dg_view.Columns.Add("trueid", "trueid");
            frm_history.dg_view.Columns["trueid"].Visible = false;
            frm_history.dg_view.Columns.Add("id", "id");
            frm_history.dg_view.Columns.Add("DepartureCity", "DepartureCity");
            frm_history.dg_view.Columns.Add("content", "content");
            frm_history.dg_view.Columns["content"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dao.BindDataGridView(frm_history.dg_view,Logistics.list);
            frm_history.Text = "历史数据";
            frm_history.Width = this.Width;
            frm_history.Height = dg_main.Height / 2;
            frm_history.Location = new Point(this.Location.X, this.Location.Y + this.Height / 2);

            frm_history.Show();
            btn_history.Text = "历史数据";
        }

        private void Main_Activated(object sender, EventArgs e)
        {
            //if(dg_main.Rows.Count>1)
            //dg_main.FirstDisplayedScrollingRowIndex = dg_main.Rows.Count-1;
            this.Text = "QQCTU物流 当前信息数量:" + dg_main.Rows.Count;
        }

        private void cmb_dress_SelectionChangeCommitted(object sender, EventArgs e)
        {/*
            Thread t_dress = new Thread(dress);
            lb_status.Text = "正在筛选数据";

            //////

            if (cmb_dress.SelectedIndex == 0)
                for (int i = 0; i < dg_main.Rows.Count; i++)
                {
                    dg_main.Rows[i].Visible = true;
                    Application.DoEvents();
                }
            if (cmb_dress.SelectedIndex == 1)
                for (int i = 0; i < dg_main.Rows.Count; i++)
                {
                    if (dg_main.Rows[i].DefaultCellStyle.ForeColor == Color.Blue)
                        dg_main.Rows[i].Visible = false;
                    else
                        dg_main.Rows[i].Visible = true;
                    Application.DoEvents();
                }
            if (cmb_dress.SelectedIndex == 2)
                for (int i = 0; i < dg_main.Rows.Count; i++)
                {
                    if (dg_main.Rows[i].DefaultCellStyle.ForeColor == Color.Blue)
                        dg_main.Rows[i].Visible = true;
                    else
                        dg_main.Rows[i].Visible = false;
                    Application.DoEvents();
                }

            */



            /////

            /*
            if (cmb_dress.SelectedIndex == 0)
            {
                t_dress.Start(0);
            }
            else if (cmb_dress.SelectedIndex == 1)
            {
                t_dress.Start(1);
            }
            else if (cmb_dress.SelectedIndex == 2)
            {
                t_dress.Start(2);
            }*/

        }

        private void dress(object obj)
        {
            int a = (int)obj;
            dg_main.Invoke(new MethodInvoker(delegate
            {
                if (a == 0)
                    for (int i = 0; i < dg_main.Rows.Count; i++)
                    {
                        dg_main.Rows[i].Visible = true;
                        Application.DoEvents();
                    }
                if (a == 1)
                    for (int i = 0; i < dg_main.Rows.Count; i++)
                    {
                        if (dg_main.Rows[i].DefaultCellStyle.ForeColor == Color.Blue)
                            dg_main.Rows[i].Visible = false;
                        else
                            dg_main.Rows[i].Visible = true;
                        Application.DoEvents();
                    }
                if (a == 2)
                    for (int i = 0; i < dg_main.Rows.Count; i++)
                    {
                        if (dg_main.Rows[i].DefaultCellStyle.ForeColor == Color.Blue)
                            dg_main.Rows[i].Visible = true;
                        else
                            dg_main.Rows[i].Visible = false;
                        Application.DoEvents();
                    }
            }));

        }

        private void dg_main_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            for (int i = 0; i < Logistics.list.Count; i++)
            {
                if (Logistics.list[i].Id.Equals(dg_main.SelectedRows[0].Cells["trueid"].Value))
                {
                    DetailInfor frm_infor = new DetailInfor();
                    frm_infor.tb_InforType.Text = Logistics.list[i].InformationType1;
                    frm_infor.tb_DepartureCity.Text = Logistics.list[i].DepartureCity1;
                    frm_infor.tb_DepartureTime.Text = Logistics.list[i].DepartureTime1;
                    frm_infor.tb_ReleaseTo.Text = Logistics.list[i].ReleaseTo1;
                    frm_infor.tb_username.Text = Logistics.list[i].UserName1;
                    frm_infor.tb_Fax.Text = Logistics.list[i].Fax1;
                    frm_infor.tb_FixedTelephone.Text = Logistics.list[i].FixedTelephone1;
                    frm_infor.tb_InformationContent.Text = Logistics.list[i].InformationContent1;
                    frm_infor.tb_MobilePhone.Text = Logistics.list[i].MobilePhone1;
                    frm_infor.tb_QQ.Text = Logistics.list[i].QQ1;
                    frm_infor.tb_ReachCity.Text = Logistics.list[i].ReachCity1;
                    frm_infor.ShowDialog();
                    return;
                }
            }


        }

        private void btn_release_Click(object sender, EventArgs e)
        {
            if (Userini.userinfor.Rows.Count < 1 || Userini.userinfor.Rows[0]["MobilePhone"].ToString().Trim().Equals(""))
            {
                MessageBox.Show("您还未完善个人信息，请先去管理中完善个人信息后再进行发布");
                return;
            }
            Release frm_release = new Release();
            frm_release.Show();
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            Search frm_search = new Search();
            frm_search.Show();
        }

        private void btn_admin_Click(object sender, EventArgs e)
        {

        }



    }
}
